import axios from 'axios';
import storage from 'store';
import notification from 'ant-design-vue/es/notification';
import { VueAxios } from './axios';
import { ACCESS_RISK_TOKEN, ACCESS_TOKEN } from '@/store/mutation-types';
import { HTTP_STATUS } from '@/utils/http';

// htpp code
const {
  AUTHENTICATE,
  FORMAT_ERROR,
  SERVER_ERROR,
  CLIENT_ERROR,
  FORBIDDEN
} = HTTP_STATUS;

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 200000 // 请求超时时间
});

// get error message
const _getErrorMessage = (data) => {
  let message = '';
  switch (typeof (data.message)) {
    case 'object':
    {
      const keys = Object.keys(data.message);
      const mesg = data.message[keys[0]];
      message = mesg.toString();
      break;
    }

    default:
      message = (data.message).toString();
      break;
  }
  message = message.toString();

  return message;
};

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    const { data, status } = error.response;

    // const { status, data } = error.response;

    const mesg = '';

    switch (status) {
      // case AUTHENTICATE:
      //   mesg = data.message;
      //   notification.error({
      //     message: 'Unauthorized',
      //     description: 'Authorization verification failed'
      //   });
      //   break;

      // case FORMAT_ERROR:
      //   notification.error({
      //     message: status.toString(),
      //     description: _getErrorMessage(data)
      //   });
      //   break;
      case CLIENT_ERROR:
      case FORBIDDEN:
        break;

      default:
        notification.error({
          message: status.toString(),
          description: _getErrorMessage(data)
        });
        break;
    }

    // 从 localstorage 获取 token
    // if (error.response.status === 403) {
    //   notification.error({
    //     message: 'Forbidden',
    //     description: data.message
    //   });
    // }
    // if (error.response.status === 401 && !(data.result && data.result.isLogin)) {

    // }
  }
  return Promise.reject(error);
};

// request interceptor
request.interceptors.request.use((config) => {
  const token = storage.get(ACCESS_TOKEN);
  // const r_token = storage.get(ACCESS_RISK_TOKEN);
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers.Authorization = `flowengine ${token}`;
    // config.headers['Authorization-RISK'] = r_token;
  }
  return config;
}, errorHandler);

// response interceptor
request.interceptors.response.use((response) => response.data, errorHandler);

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, request);
  }
};

export default request;

export {
  installer as VueAxios,
  request as axios
};
